package com.jz.controller;

import com.jz.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Value("${config.file.filePath}")
    private String filePath;
    @Value("${config.file.resourceHandler}")
    private String resourceHandler;

    /**
     * 文件上传，因为只是演示，所以使用 @ResponseBody 将结果直接返回给页面
     *
     * @param multipartFile
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultUtil uploadFile(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return ResultUtil.error("上传文件为空");
        }
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        String fileName = multipartFile.getOriginalFilename();
        String fileServerPath = basePath + resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + fileName;
        logger.info("文件访问路径：" + fileServerPath);
        File saveFile = new File(filePath, fileName);
        //文件保存
        multipartFile.transferTo(saveFile);
        return ResultUtil.success(fileServerPath);
    }

}
